#include "Add.h"
#include "ui_Add.h"
#include "Manage.h"
#include <QSqlError>
#include <QBitmap>
#include <QStyleOption>
#include <QMouseEvent>
#include <QPainter>
#include "mymessagebox.h"

Add::Add(Manage *manage,QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Add)
    , manageWindow(manage)
    , model(new QStringListModel(this))
{
    ui->setupUi(this);

    // 隐藏原生标题栏
    setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);

    // 防止窗口背景透明
    setAttribute(Qt::WA_TranslucentBackground, false);

    // 加载员工信息到QListView
    loadEmployeeList();
}

Add::~Add()
{
    delete ui;
}

// 实现窗口拖动功能
void Add::mousePressEvent(QMouseEvent *event)
{
    // 检查是否点击了自定义标题栏
    if (event->button() == Qt::LeftButton && event->pos().y() <= 60) {
        m_isTitleBarClicked = true;
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    } else {
        m_isTitleBarClicked = false;
        // 让事件继续传播，确保其他控件能响应点击事件
        QWidget::mousePressEvent(event);
    }
}

void Add::mouseMoveEvent(QMouseEvent *event)
{
    // 只有在点击了标题栏之后才允许拖动
    if (m_isTitleBarClicked && (event->buttons() & Qt::LeftButton)) {
        move(event->globalPos() - m_dragPosition);
        event->accept();
    } else {
        // 让事件继续传播，确保其他控件能响应移动事件
        QWidget::mouseMoveEvent(event);
    }
}

void Add::paintEvent(QPaintEvent *event)
{
    // 1. 绘制样式（QSS）
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); // 绘制样式

    // 2. 设置掩码，约定 painter 绘制区域
    QBitmap bmp(this->size());
    bmp.fill(Qt::white); // 填充 bitmap

    QPainter painter(&bmp);
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black); // 掩码值
    painter.drawRoundedRect(bmp.rect(), 30, 30); // 在 bitmap 中绘制圆角矩形

    // 设置掩码以确定本控件可绘制区域
    setMask(bmp);

    // 调用基类的 paintEvent
    QWidget::paintEvent(event);
}

void Add::on_returnButton_clicked()
{
    this->close();
    manageWindow->refreshPageData();
    manageWindow->show();
}


void Add::on_no_clicked()
{
    this->close();
    manageWindow->refreshPageData();
    manageWindow->show();
}


void Add::on_yes_clicked()
{
    QString empNum = ui->num->text(); // 工号
    QString empName = ui->name->text(); // 姓名

    if (empNum.isEmpty() || empName.isEmpty()) {
        // QMessageBox::warning(this, "错误", "工号或姓名不能为空");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("工号或姓名不能为空");
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    QSqlQuery query;

    // 查询工号是否存在
    query.prepare("SELECT 工号 FROM EmployeeInfo WHERE 工号 = :empNum");
    query.bindValue(":empNum", empNum);
    query.exec();

    if (query.next()) {
        // 工号已存在
        // QMessageBox::warning(this, "警告", "该工号已存在");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("警告");
        msgBox.setText("该工号已存在");
        msgBox.setButton("确定");
        msgBox.exec();
    } else {
        // 工号不存在，插入数据
        query.prepare("INSERT INTO EmployeeInfo (工号, 姓名, 密码, 标签号) VALUES (:empNum, :empName, '', 0)");
        query.bindValue(":empNum", empNum);
        query.bindValue(":empName", empName);

        if (query.exec()) {
            // 插入成功
            // QMessageBox::information(this, "成功", "已成功添加");
            MyMessageBox msgBox;
            msgBox.setWindowTitle("成功");
            msgBox.setText("已成功添加");
            msgBox.setButton("确定");
            msgBox.exec();

            // 第一个表：创建名为 `empNum_empName` 的表，字段为考勤组号 INT
            QString attendanceTableName = QString("`%1_%2`").arg(empNum).arg(empName);

            QSqlQuery query;
            QString createAttendanceTableQuery = QString("CREATE TABLE IF NOT EXISTS %1 (考勤组号 INT)").arg(attendanceTableName);

            query.prepare(createAttendanceTableQuery);
            if (query.exec()) {
                // QMessageBox::information(this, "成功", QString("成功为 %1 创建了考勤组表").arg(empName));
                MyMessageBox msgBox;
                msgBox.setWindowTitle("成功");
                msgBox.setText(QString("成功为 %1 创建了考勤组表").arg(empName));
                msgBox.setButton("确定");
                msgBox.exec();
            } else {
                // QMessageBox::critical(this, "错误", "创建考勤组表时出错: " + query.lastError().text());
                MyMessageBox msgBox;
                msgBox.setWindowTitle("错误");
                msgBox.setText("创建考勤组表时出错: " + query.lastError().text());
                msgBox.setButton("确定");
                msgBox.exec();
                return;  // 如果创建第一个表失败，直接返回
            }

            // 第二个表：创建名为 `empNum_empName_1` 的表，字段为旷工日期 DATE
            QString absenteeismTableName = QString("`%1_%2_1`").arg(empNum).arg(empName);

            QString createAbsenteeismTableQuery = QString("CREATE TABLE IF NOT EXISTS %1 (考勤组号 INT,旷工日期 DATE)").arg(absenteeismTableName);

            query.prepare(createAbsenteeismTableQuery);
            if (query.exec()) {
                // QMessageBox::information(this, "成功", QString("成功为 %1 创建了旷工日期表").arg(empName));
                MyMessageBox msgBox;
                msgBox.setWindowTitle("成功");
                msgBox.setText(QString("成功为 %1 创建了旷工日期表").arg(empName));
                msgBox.setButton("确定");
                msgBox.exec();
            } else {
                // QMessageBox::critical(this, "错误", "创建旷工日期表时出错: " + query.lastError().text());
                MyMessageBox msgBox;
                msgBox.setWindowTitle("错误");
                msgBox.setText("创建旷工日期表时出错: " + query.lastError().text());
                msgBox.setButton("确定");
                msgBox.exec();
            }

            // 添加到员工考勤总表，所有统计值默认为0
            query.prepare(R"(
                INSERT INTO EmployeeAttendanceSummary (工号, 姓名, 打卡总数, 已打卡数, 补签次数, 请假次数, 未打卡数)
                VALUES (:empNum, :empName, 0, 0, 0, 0, 0)
            )");
            query.bindValue(":empNum", empNum);
            query.bindValue(":empName", empName);
            query.exec();

            // 清空 num 和 name 文本框
            ui->num->clear();
            ui->name->clear();

            // 更新员工列表
            loadEmployeeList();
        } else {
            // QMessageBox::critical(this, "错误", "无法添加员工: " + query.lastError().text());
            MyMessageBox msgBox;
            msgBox.setWindowTitle("错误");
            msgBox.setText("无法添加员工: " + query.lastError().text());
            msgBox.setButton("确定");
            msgBox.exec();
        }
    }
}

void Add::loadEmployeeList()
{
    QSqlQuery query;
    query.exec("SELECT 工号, 姓名, 密码, 标签号 FROM EmployeeInfo");  // 查询工号、姓名、密码、标签号

    QStringList employeeList;
    while (query.next()) {
        QString empNum = query.value(0).toString();   // 工号
        QString empName = query.value(1).toString();  // 姓名
        QString password = query.value(2).toString(); // 密码
        int tagNumber = query.value(3).toInt();       // 标签号

        // 判断密码和标签号的状态
        QString employeeStatus;
        if (password.isEmpty()) {
            employeeStatus = empNum + "-" + empName + "-未认证";  // 密码为空，未认证
        } else if (tagNumber == 0) {
            employeeStatus = empNum + "-" + empName + "-未录入";  // 标签号为0，未录入
        } else {
            employeeStatus = empNum + "-" + empName + "-已录入";  // 标签号不为0，已录入
        }

        employeeList << employeeStatus;
    }

    // 将数据加载到QListWidget
    model->setStringList(employeeList);
    ui->list->setModel(model);

}
